package io.afu.baseframework.annotations.impls;

import io.afu.baseframework.annotations.TimeValidator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

public class TimeValidatorImpl implements ConstraintValidator<TimeValidator,String> {
    private String format;

    private boolean allowEmpty;

    @Override
    public void initialize(TimeValidator timeValidator){
        format = timeValidator.format();
        allowEmpty = timeValidator.allowEmpty();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (format != null && !"".equals(format)){
            if (null == s || "".equals(s)){
                if (allowEmpty){
                    return true;
                }
            }else {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
                try {
                    simpleDateFormat.setLenient(false);
                    simpleDateFormat.parse(s);
                    return true;
                }catch (Exception e){
                    return false;
                }
            }
        }
        return true;
    }
}
